const express = require('express');
const cors = require('cors');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const path = require('path');
const createError = require('http-errors');

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const dataRouter = require('./routes/data');
const VideoRouter = require('./routes/video'); // 加在文件头部其它 require 下面

const app = express();

// 使用 Express 内置的中间件替代 body-parser
app.use(express.urlencoded({ extended: false })); // 替代 bodyParser.urlencoded
app.use(express.json()); // 替代 bodyParser.json

app.use(cors());
app.use(logger('dev'));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 添加 favicon.ico 的静态文件服务
app.use('/favicon.ico', express.static(path.join(__dirname, 'favicon.ico')));

app.use('/', indexRouter);
app.use('/api/users', usersRouter);
app.use('/api/data', dataRouter);
app.use('/api/video', VideoRouter); // 保持你的路由前缀

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.json({
    message: err.message,
    error: req.app.get('env') === 'development' ? err : {}
  });
});

module.exports = app;